﻿@page "/mainplan/bind/{Id}"
@inject IMainPlanService MainPlanService
@inject IProjectService ProjectService
@inject NavigationManager NavigationManager
@inject IJSRuntime JsRuntime

<PageTitle>主计划绑定项目</PageTitle>

<span>@_mainPlanDto.Number-@_mainPlanDto.Name</span>

<EditForm class="mt-3" Model="_mainPlanDto" OnSubmit="Save">
    <div class="input-group mb-2">
        <span class="input-group-text">搜索</span>
        <input class="form-control" placeholder="Search" @bind-value="@_search" @oninput="@Search" />
    </div>
    @if (_projectDtos.Count!=0)
    {
        <fieldset>
            <legend>请选择需要绑定的项目:</legend>
            @foreach (var project in _projectDtos)
            {
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="projects" @bind-value="@project.Id" @oninput="Checked">
                    <label class="form-check-label" >
                        @project.OdpNumber - @project.Name
                    </label>
                </div>
            }
        </fieldset>
    }
    else
    {
        <span>没搜索到项目...</span>
    }
    
    <CompSaveCancelButtons CancelUrl="" />
</EditForm>

@code {
    [Parameter]
    public string Id { get; set; }
    private MainPlanDto? _mainPlanDto = new();

    private string _search = string.Empty;
    private List<ProjectDto> _projectDtos = new();    
    protected override async Task OnInitializedAsync()
    {
        var result = await MainPlanService.GetFirstOrDefaultAsync(Guid.Parse(Id));
        _mainPlanDto = result.Result;

        _search = _mainPlanDto.Number.Substring(0, 9);
        Search(new ChangeEventArgs { Value = _search });
        StateHasChanged();
    }


    public async Task Save()
    {
        if (_mainPlanDto!.ProjectId==null||_mainPlanDto!.ProjectId==Guid.Empty)
        {
            await JsRuntime.InvokeVoidAsync("alert", "请选择项目");
            return;
        }

        var result = await MainPlanService.UpdateStatusesAsync(Guid.Parse(Id), _mainPlanDto);
        if (result.IsSuccessStatusCode) NavigationManager.NavigateTo("");
    }
    private async void Search(ChangeEventArgs e)
    {
        _search=e.Value!.ToString()!;
        _projectDtos.Clear();
        _projectDtos.AddRange(await ProjectService.GetBlazorBindAsync(_search));

        StateHasChanged();
    }

    private void Checked(ChangeEventArgs e)
    {
        var id = Guid.Parse(e.Value!.ToString()!);
        _mainPlanDto!.ProjectId = id;
    }
}
